#include <any>
#include <string>
#include <unordered_map>
#include <typeindex>
#include <typeinfo>
#include <stdexcept>
#include <iostream>

struct ConfigValue {
    std::any value;
    std::type_index type = typeid(void);  // Default type is void

    ConfigValue() = default;  // Default constructor

    ConfigValue(std::any value, std::type_index type)
        : value(value), type(type) {}
};

class ConfigManager {
public:
    // 设置配置项
    template<typename T>
    void set(const std::string& key, const T& value) {
        // 直接在容器中构造元素
        items_.emplace(key, ConfigValue(value, typeid(T)));
    }

    // 读取配置项，支持类型安全的访问和默认值
    template<typename T>
    T get(const std::string& key, const T& defaultValue = T()) const {
        auto it = items_.find(key);
        if (it != items_.end() && it->second.type == typeid(T)) {
            try {
                return std::any_cast<T>(it->second.value);
            } catch (const std::bad_any_cast&) {
                throw std::runtime_error("Type mismatch, this should never happen.");
            }
        }
        return defaultValue;
    }

    // 检查配置项是否存在
    bool has(const std::string& key) const {
        return items_.find(key) != items_.end();
    }

    // 检查配置项类型是否匹配
    template<typename T>
    bool isTypeMatch(const std::string& key) const {
        auto it = items_.find(key);
        return it != items_.end() && it->second.type == typeid(T);
    }

private:
    std::unordered_map<std::string, ConfigValue> items_;
};

int main() {
    ConfigManager config;

    // 设置不同类型的配置项
    config.set("max_connections", 100);
    config.set("db_name", std::string("mydatabase"));
    config.set("cache_enabled", true);

    // 尝试获取配置项，使用默认值作为后备
    int maxConnections = config.get<int>("max_connections", 10);
    std::string dbName = config.get<std::string>("db_name", "defaultdb");
    bool cacheEnabled = config.get<bool>("cache_enabled", false);

    std::cout << "Max connections: " << maxConnections << std::endl;
    std::cout << "DB Name: " << dbName << std::endl;
    std::cout << "Cache Enabled: " << std::boolalpha << cacheEnabled << std::endl;

    // 检查配置项存在性和类型匹配
    if (config.has("max_connections") && config.isTypeMatch<int>("max_connections")) {
        std::cout << "Max connections is correctly configured." << std::endl;
    }

    return 0;
}